package com.hb.trade.api.im.chat.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.core.pojo.im.entity.ChatRecord;
import com.hb.core.pojo.im.entity.ChatRecordContent;
import com.hb.core.pojo.im.mapper.ChatRecordContentMapper;
import com.hb.trade.api.im.chat.manager.ChatRecordContentManager;
import com.hb.trade.api.im.chat.service.ChatRecordContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.fzzn.core.model.user.layim.LayImUser;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 聊天记录表 服务实现类
 *
 * @author zhaojk
 * @since 2021-12-30
 */
@Service
public class ChatRecordContentServiceImpl extends ServiceImpl<ChatRecordContentMapper, ChatRecordContent> implements ChatRecordContentService {

    @Override
    public void saveFromRecord(ChatRecord record) {
        if (record == null) {
            return;
        }
        Long msgId = record.getMsgId();
        if (msgId == null) {
            // msgId不存在不会保存
            return;
        }
        // 先查询该消息是否已存在
        QueryWrapper<ChatRecordContent> wrapper = ChatRecordContent.wrapper();
        wrapper.eq("msg_id", msgId);
        long count = count(wrapper);
        if (count > 0) {
            // 已存在的消息不再保存
            return;
        }
        // 从聊天内容中获取聊天类型和正文内容
        String contentJSONStr = record.getContent();
        if (!JSONUtil.isJsonObj(contentJSONStr)) {
            // 聊天内容不是json结构, 不保存, 可能是其他方法调用的
            return;
        }
        // 构建数据
        JSONObject recordJSON = JSONUtil.parseObj(contentJSONStr);
        ChatRecordContent recordContent = record.to(ChatRecordContent.class);
        // 聊天类型
        String type = recordJSON.getJSONObject("contentData").getStr("type");
        recordContent.setType(type);
        // 聊天正文
        String contentText = recordJSON.getJSONObject("contentData").getStr("content");
        recordContent.setRecordContent(contentText);
        recordContent.buildBaseData(1);
        // 保存
        save(recordContent);
    }

    @Override
    public Page<LayImUser> historyRecord(Long fromId, Long toId, String type) {
        ChatRecordContent recordContent = new ChatRecordContent();
        recordContent.setFromId(fromId);
        recordContent.setType(type);
        recordContent.setToId(toId);
        return historyRecord(recordContent);
    }

    @Override
    public Page<LayImUser> historyRecord(ChatRecordContent content) {
        String type = content.getType();
        if (StrUtil.isEmpty(type)) {
            return null;
        }
        ChatRecordContentManager contentManager = content.to(ChatRecordContentManager.class);
        QueryWrapper<ChatRecordContent> wrapper = contentManager.getWrapper();

        Page<ChatRecordContent> pages = content.pages();
        // hasPage方法如果返回true, 表示page参数由前端传递
        // hasPage方法返回false, 表示没有传参数, 查询最后一页的数据
        if (!content.hasPage()) {
            // 查询数据总数, 确定最后一页是第几页
            long count = count(wrapper);
            // 每页条数
            long size = pages.getSize();
            // 计算最后一页的页码
            long lastPage = count / size;

            if (count % size != 0) {
                lastPage++;
            }
            pages.setCurrent(lastPage);
        }

        // 查询实际数据
        Page<ChatRecordContent> pageRecords = page(pages, wrapper);

        // 操作数据集合对象
        List<ChatRecordContent> records = pageRecords.getRecords();
        if (CollUtil.isEmpty(records)) {
            return null;
        }
        // 用set集合做去重
        Set<LayImUser> historyRecords = CollUtil.set(true);
        for (ChatRecordContent record : records) {
            // 解析聊天内容
            ChatRecordContentManager recordContentManager = record.to(ChatRecordContentManager.class);
            LayImUser imUserRecord = recordContentManager.parseRecordContent();
            if (imUserRecord == null) {
                continue;
            }
            historyRecords.add(imUserRecord);
        }

        Page<LayImUser> pageRecordData = new Page<>();
        // 实际显示的数据
        pageRecordData.setRecords(CollUtil.list(false, historyRecords));
        // 总页数
        pageRecordData.setPages(pageRecords.getPages());
        // 当前页数
        pageRecordData.setCurrent(pageRecords.getCurrent());
        // 数据总条数
        pageRecordData.setTotal(pageRecords.getTotal());
        return pageRecordData;
    }
}
